package com.example.influxdb01.utils;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

/**
 * @author yihao
 * @description
 * @time 2022/04/26 11:18:20
 */
public class CSVWriter {
    private static final Logger logger = LoggerFactory.getLogger(CSVWriter.class);

    /**
     * 写CSV文件
     * @param csvFile csv文件名称
     * @param fileHeader 文件头
     * @param content 内容
     * @throws IOException
     */
    public static void write(final String csvFile, final String[] fileHeader, List<String[]> content)
            throws IOException {
        //可追加
        FileWriter fw = new FileWriter(csvFile, true);
        BufferedWriter writer = new BufferedWriter(fw);
        //BufferedWriter writer = Files.newBufferedWriter(Paths.get(csvFile));
        //不要文件头，可以在DeFAULT.WithHeader()
        CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(fileHeader));

        for (String[] c : content) {
            csvPrinter.printRecord(Arrays.asList(c));
        }
        csvPrinter.flush();
        logger.info( "====> 成功写入CSV文件。文件路径：" + csvFile );

    }


}
